#encoding: UTF-8

java_import [de.recipeminer.persistence.Db4oHelpers,
             de.recipeminer.crawling.chefkoch.ChefkochJsonRecipe,
             de.recipeminer.tools.Tools]

java_import(java.lang.String) {'JString'}

module Workflow
  
  module Workflow 
    def run
      begin
        execute   
      rescue Exception => e
        exception_cleanup
        puts "Exception while execution workflow #{self.class}"        
        raise e
      end
    end

    protected
    def exception_cleanup
    end
  end
  
  class DatabaseWorkflow
    include Workflow

    def initialize
      @db4o = Db4oHelpers.current_database
    end
    protected :initialize

    protected
    def exception_cleanup
      @db4o.rollback
      @db4o.close_all_sessions
    end
  end

  class UpdateUUIDs < DatabaseWorkflow
    def initialize(id_regex, uuid_template)
      super()
      @id_regex = id_regex
      @uuid_template = uuid_template
    end

    protected
    def execute
      result = @db4o.query(ChefkochJsonRecipe.java_class.to_java)
      result.each do |r|
        @id_regex.match(r.uuid)
        new_uuid = @uuid_template.sub('§', $1)
        Tools.set_private_field(r, 'UUID', JString.java_class, new_uuid.to_java)
        @db4o.store(r.to_java)
      end
      @db4o.commit
      @db4o.close_all_sessions
    end
  end
end